<template lang="pug">
     el-card
        div(slot="header" class="clearfix")
            div(class="pull-right")
                el-button(type="primary" @click="savePermission") 保存 
        el-table(:data="resources" @selection-change="onselect" ref="resourceTable")
                el-table-column(type="selection")
                el-table-column(prop="name" label="资源名")
                el-table-column(prop="url" label="资源路径")
                el-table-column(prop="applicationName" label="应用")
</template>
<script>
import _axios from "@/plugin/axios";
export default {
  name: "rms-resource-panel",

  data: function() {
    return {
      resources: [],

      selectedRows: []
    };
  },

  props: {
    roleId: { type: String }
  },

  watch: {
    roleId: function() {
      this.getResourceByRoleId();
    }
  },

  methods: {
    getResourceByRoleId: function() {
      var data = { roleId: this.roleId };
      console.log(data);
      var options = {
        url: "/role/getResourceByRole",
        method: "post",
        data: data
      };

      var vm = this;
      _axios(options).then(function(res) {
        vm.resources = res;
        vm.checkRow();
      });
    },

    onselect: function(rows) {
      this.selectedRows = rows; // 选中的数据缓存起来
    },

    // 解析出有权限和没权限的数据
    resolveHasPermission: function() {
      if (!this.resources.length) return;

      for (var index2 = 0; index2 < this.resources.length; index2++) {
        var resource = this.resources[index2];

        var hasPermission = false;
        for (var index = 0; index < this.selectedRows.length; index++) {
          var row = this.selectedRows[index];

          if (resource.id !== row.id) continue;
          hasPermission = true;
          break;
        }
        resource.hasPermission = hasPermission; // 把数据设置为
      }
    },

    checkRow: function() {
      if (!this.resources.length) return;
      var vm = this;
      this.$nextTick(function() {
        for (var index2 = 0; index2 < this.resources.length; index2++) {
          var resource = this.resources[index2];
          var checked = resource.hasPermission;

          vm.$refs.resourceTable.toggleRowSelection(resource, checked);
        }
      });
    },

    savePermission: function() {
      this.resolveHasPermission(); // 解析出有权限和没权限的数据

      var data = { models: this.resources };

      var options = { url: "/role/savePermission", method: "post", data: data };

      _axios(options).then(res => {
        this.$message.success("保存成功");
      });
    }
  },

  created: function() {
    if (!this.roleId) return;
    this.getResourceByRoleId();
  }
};
</script>